package sessions;

import java.util.Hashtable;

import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.rmi.PortableRemoteObject;

import org.jboss.ejb3.annotation.RemoteBinding;



import entities.AdminEB;
import entities.RegistratoEB;
import exceptions.ArgomentoNonValido;





@Stateless
//@RemoteBinding(jndiBinding="UtenteSBRemote")
public class UtenteSB implements UtenteSBRemote  {

	
	@PersistenceContext(unitName="swimv2DB")
	private EntityManager manager;
	
	//copiato
	public static Context getInitialContext() throws NamingException {

		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL,"localhost:1099");

		return new InitialContext(env);
	}
	
	@Override
	public RegistratoSBRemote loginRegistrato (String mail, String nomeU, String password) 		throws ArgomentoNonValido {
		
		
		RegistratoEB registr = manager.find(RegistratoEB.class, mail);
		if(registr != null) {
			if(registr.getNomeU().equals(nomeU) && registr.getPassword().equals(password)){
				try {
					Context jndiContext = getInitialContext();
					Object registrRem= jndiContext.lookup("RegistratoSBRemote");
					RegistratoSBRemote rif = (RegistratoSBRemote) PortableRemoteObject.narrow(registrRem,RegistratoSBRemote.class);
					HashList.addHash(mail.hashCode()+password.hashCode()+nomeU.hashCode());
					return rif;
					
				} catch (NamingException e) {
					e.printStackTrace();
				}
				
			}
				
			
		}
		
		return null;
	}

	@Override
	public AdminSBRemote loginAdmin(String mail, String nomeU, String password) throws ArgomentoNonValido {
		
		AdminEB admin = manager.find(AdminEB.class, mail);
	if(admin != null) {
		if(admin.getNomeU().equals(nomeU) && admin.getPassword().equals(password)){
			try {
				Context jndiContext = getInitialContext();
				Object adminRem= jndiContext.lookup("AdminSBRemote");
				AdminSBRemote rif = (AdminSBRemote) PortableRemoteObject.narrow(adminRem,AdminSBRemote.class);
				HashList.addHash(mail.hashCode()+password.hashCode()+nomeU.hashCode());
				return rif;
				
			} catch (NamingException e) {
				e.printStackTrace();
			}
			
		}
			
		
	}
	
	return null;
}

	@Override
	public boolean registrazione(String mail, String nomeU, String password, String nome, String cognome, String dataN, String cf)
			throws ArgomentoNonValido {
		RegistratoEB reg = new RegistratoEB(cf, nomeU, password, nome, cognome, dataN, cf);

		if(manager.find(RegistratoEB.class, reg.getMail()) == null) {
			manager.persist(reg);
			return true;
		}
		else {
			return false;
		}
	}
	
	
	
	
}
